package com.foreveross.fetl.queue;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.foreveross.fetl.application.ICsairReportApplication;
import com.foreveross.fetl.application.ILogMessageApplication;
import com.foreveross.fetl.common.vo.TaskInfoXmlBean;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.util.StringUtils;
import com.foreveross.fetl.vo.LogMessageVO;

@Component
public class CsairReportPreprocess {

	private static Logger log = Logger.getLogger("CsairReport");
	
	@Inject
	private ILogMessageApplication logMessageApplication;
	
	@Inject ICsairReportApplication csairReportApplication;
	
	private int tasksNumber;//任务数 多少条rowkey
	
	private int failuresNumber;//失败数
	
	private int insertNumber; //插入条数 
	
	private long excuteStartTime;
	
	private Date execute_startTime;
	
	private String taskTime=null;
	
	private LogMessageVO logMessage;
	
	private int domesticTasksNumber;
	private int domesticFailuresNumber;
	private int domesticInsertNumber;
	private long domesticStartTime;
	private Date domesticStrTime;
	private String domesticTaskTime;
	private LogMessageVO domesticLogMessage;
	
	public void  rollBackNumber(){
		tasksNumber=0;
		failuresNumber=0;
		insertNumber=0;
		excuteStartTime = System.currentTimeMillis();
		LogMessageVO startLogMessage =new LogMessageVO();
		startLogMessage.setExecuteClass("CsairReportPreprocess");
		startLogMessage.setExecuteName("南航国际报表");
		startLogMessage.setExecuteStartTime(new Date());
		startLogMessage.setExecuteType(1);
		logMessageApplication.create(startLogMessage);
		logMessage = startLogMessage;
	}
	
	public void rollDomesticNumber(){
		domesticTasksNumber=0;
		domesticFailuresNumber=0;
		domesticInsertNumber=0;
		domesticStartTime=System.currentTimeMillis();
		LogMessageVO startLogMessage =new LogMessageVO();
		startLogMessage.setExecuteClass("CsairReportPreprocess");
		startLogMessage.setExecuteName("南航国内报表");
		startLogMessage.setExecuteStartTime(new Date());
		startLogMessage.setExecuteType(1);
		logMessageApplication.create(startLogMessage);
		domesticLogMessage = startLogMessage;
		
	}
	
	public void execute(){
		final Calendar c = Calendar.getInstance();
		c.add(Calendar.HOUR_OF_DAY, -1);
		rollBackNumber();
		taskTime=DateUtils.format(c.getTime(), "yyyy-MM-dd HH");
		try {
			process(c.getTime(), new Date());
		} catch (Exception e) {
			this.saveOrUpdateLog(logMessage, 3, 1, StringUtils.getStackTrace(e));
		}
		this.saveOrUpdateLog(logMessage, 2, 1, null);
		
		rollDomesticNumber();
		domesticTaskTime=DateUtils.format(c.getTime(), "yyyy-MM-dd HH");
		try {
			processDomestic(c.getTime(), new Date());
		} catch (Exception e) {
			this.saveOrUpdateLog(domesticLogMessage, 3, 2, StringUtils.getStackTrace(e));
		}
		this.saveOrUpdateLog(domesticLogMessage, 2, 2, null);
	}
	
	public void manualExecute(final String start,String time){
		this.rollBackNumber();
		try {
		List<String> timeList = Arrays.asList(time.split(";"));
		Calendar c = Calendar.getInstance();
		taskTime = start + " " +time;
		for (String s : timeList) {
			String str =start;
			str += s;
			Date startTime = DateUtils.parse(str, "yyyyMMddHH");
			c.setTime(startTime);
			c.add(Calendar.HOUR_OF_DAY, +1);
			Date endTime = c.getTime();
			this.process(startTime, endTime);
		}
		this.saveOrUpdateLog(logMessage, 2, 1, null);
		} catch (Exception e) {
			this.saveOrUpdateLog(logMessage, 3, 1, StringUtils.getStackTrace(e));
		log.error(StringUtils.getStackTrace(e));
	}
}
	
	public void manualDomesticExecute(final String start,String time){
		this.rollDomesticNumber();
		try {
			List<String> timeList = Arrays.asList(time.split(";"));
			Calendar c = Calendar.getInstance();
			domesticTaskTime = start + " " +time;
			for (String s : timeList) {
				String str =start;
				str += s;
				Date startTime = DateUtils.parse(str, "yyyyMMddHH");
				c.setTime(startTime);
				c.add(Calendar.HOUR_OF_DAY, +1);
				Date endTime = c.getTime();
				this.processDomestic(startTime, endTime);
			}
			} catch (Exception e) {
				this.saveOrUpdateLog(domesticLogMessage, 3, 2, StringUtils.getStackTrace(e));
				log.error(StringUtils.getStackTrace(e));
			}
		this.saveOrUpdateLog(domesticLogMessage, 2, 2, null);
	}
	
	
	public void process(final Date start, final Date end) {
		log.info("CsairReportPreprocess start:"
				+ DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
		execute_startTime=new Date();
		List<String> taskLines=TaskInfoXmlBean.getInternationalLines();
		
		if(taskLines==null || taskLines.size()==0){
			log.info("航线为空");
			return;
		}
		List<String> chanels=new ArrayList<String>();
	//	chanels.add("20005");//中国南方航空官网
		chanels.add("00001");//淘宝旅游网
		chanels.add("00002");//去哪儿网
		
		List<String> airCompanys =new ArrayList<String>();
		airCompanys.add("20005");
		
	/*	//..........纠结的南航
		String[] SpaLine = { "CAN-ATL", "CAN-JFK", "CAN-SFO", "CAN-ORD",
				"CAN-MEM", "CAN-MAN", "CAN-ROM", "CAN-MAD", "CAN-BRU",
				"CAN-FRA", "CAN-YWG", "CAN-YTO", "CAN-YMQ", "CAN-CHC",
				"CAN-ADL", };
		for(String str: SpaLine){
			String[] lines=str.split("-");
			Calendar cFlightDate = Calendar.getInstance();
			cFlightDate.setTime(start);
			//cFlightDate.add(Calendar.DAY_OF_MONTH, 63);
			Date date =DateUtils.parse("20140320", "yyyyMMdd");
			int c;
			c=csairReportApplication.createReport(
					chanels, lines[0], lines[1], start,
					date,2,0);
			System.out.println(c+"sigle"+lines[0]+ "   "+  lines[1]);
			c=csairReportApplication.createReport(
					chanels, lines[0], lines[1], start,
					date,2,1);
			System.out.println(c+"double"+lines[0]+ "   "+ lines[1]);
		}
		//............
*/		
		for(String str:taskLines){
			String[] lines=str.split("-");
			Calendar cFlightDate = Calendar.getInstance();
			cFlightDate.setTime(start);
			int[] days ={7,8,15};//7天 15天 30天
			for(int i : days){
				cFlightDate.add(Calendar.DAY_OF_MONTH, i);
				try {
					tasksNumber++;
					insertNumber += csairReportApplication.createReport(airCompanys,
							chanels, lines[0], lines[1], start,
							cFlightDate.getTime(),2,0);
				} catch (Exception e) {
					e.printStackTrace();
					failuresNumber++;
				}
				try {
					tasksNumber++;
					insertNumber += csairReportApplication.createReport(
							airCompanys,chanels, lines[0], lines[1], start,
							cFlightDate.getTime(),2,1);
				} catch (Exception e) {
					e.printStackTrace();
					failuresNumber++;
				}
			}
		
		}
	}
	
	
	public void  processDomestic(final Date start, final Date end){
		log.info("CsairReportPreprocess domestic start:"
				+ DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
		domesticStrTime=new Date();
		List<String> airCompanys =getAirCompanys();
		List<String> taskLines=null;
		List<String> chanels=new ArrayList<String>();
		chanels.add("00001");//淘宝旅游网
		chanels.add("00002");//去哪儿网
		
		for(String company:airCompanys ){
			List<String> companys =new ArrayList<String>();	
			companys.add(company);
			taskLines=this.getAirLines(company);
			if(taskLines==null || taskLines.size()==0){
				log.info("航线为空");
				return;
			}
			for(String str:taskLines){
				String[] lines=str.split("-");
				Calendar cFlightDate = Calendar.getInstance();
				cFlightDate.setTime(start);
				for(int i =0;i<=7;i++){
					try {
						domesticTasksNumber++;
						domesticInsertNumber += csairReportApplication.createReport(companys,
									chanels, lines[0], lines[1], start,
									cFlightDate.getTime(),1,0);
						cFlightDate.add(Calendar.DAY_OF_MONTH, 1);
					} catch (Exception e) {
						e.printStackTrace();
						domesticFailuresNumber++;
					}
				}
			}
		}
	}
	
	private void saveOrUpdateLog(LogMessageVO vo,int executeType,int type,String result){
		LogMessageVO logMes =new LogMessageVO();
		if(null!=vo){
			logMes=logMessageApplication.getOneLogMessage(vo.getExecuteClass(), vo.getExecuteName(), vo.getExecuteStartTime(), vo.getExecuteType());
		}
		logMes.setExecuteClass("CsairReportPreprocess");
		logMes.setExecuteType(executeType);
		if(result!=null){
			if(result.length()>200){
				result=result.substring(0, 199);
			}
			logMes.setResult(result);
		}
		if(1==type){
			logMes.setExecuteName("南航国际报表");
			logMes.setExecuteStartTime(execute_startTime);	
			logMes.setExecuteEndTime(new Date());
			logMes.setFailuresNumber(failuresNumber);
			logMes.setTasksNumber(tasksNumber);
			logMes.setInsertNumber(insertNumber);
			logMes.setTaskTime(taskTime);
			logMes.setExecuteTotalTime(System.currentTimeMillis()-excuteStartTime);
		}
		if(2==type){
			logMes.setExecuteName("南航国内报表");
			logMes.setExecuteStartTime(domesticStrTime);
			logMes.setExecuteEndTime(new Date());
			logMes.setFailuresNumber(domesticFailuresNumber);
			logMes.setTasksNumber(domesticTasksNumber);
			logMes.setInsertNumber(domesticInsertNumber);
			logMes.setExecuteTotalTime(System.currentTimeMillis()-domesticStartTime);
			logMes.setTaskTime(domesticTaskTime);	
		}
		
		if(logMes.getId()!=null && logMes.getId()!=0){
			logMessageApplication.update(logMes);
		}else{
			logMessageApplication.create(logMes);
		}
		
		
	}
	
	private List<String> getAirCompanys(){
		List<String> airCompanys =new ArrayList<String>();
		String[] strs={"20002","20003",
				"20005","20007","20009",
				"20011","20012","20013","20014","20015",
				"20016","20018"};
		for(String str :strs){
			airCompanys.add(str);
		}
		return airCompanys;
	}
	
	private List<String> getAirLines(String channel){
		
		Map<String ,String[]> map =new HashMap<String ,String[]>();
		
		String[] s20009 = { "SZX-DLC", "SZX-HLD", "SZX-HRB", "SZX-NGB",
				"SZX-CGO", "DLC-SZX", "DLC-NGB", "HLD-SZX", "HLD-HRB",
				"HRB-SZX", "HRB-HLD", "NGB-SZX", "CGO-SZX", "NGB-DLC" };
		map.put("20009", s20009);//东海
		
		String[] s20011 = { "CAN-HGH", "CAN-CKG", "PEK-HET", "HET-URC",
				"PEK-LJG", "LJG-JHG", "HET-PEK", "PEK-ERL", "HET-WUH",
				"HET-HAK", "XIY-TNA", "KWL-XMN", "PEK-JXA", "NKG-LJG" };
		map.put("20011", s20011);//首都
		
		String[] s20016 = { "PEK-SHA", "BAV-SHA", "CKG-SHA", "CAN-SHA",
				"SHA-PEK", "SHA-BAV", "SHA-CKG", "SHA-HRB", "SHA-HAK",
				"XIY-SHA", "TYN-HGH", "TSN-SHA", "SZX-SHA",	"SHE-SHA"};
		map.put("20016", s20016);//吉祥
		
		String[] s20003 = { "CTU-PEK", "CAN-CTU", "CKG-SZX", "CKG-SHA",
				"CTU-HRB", "CTU-CSX", "CTU-CAN", "CTU-HAK", "CTU-TAO",
				"PEK-CTU", "CTU-NKG", "SHA-CKG", "SZX-CKG", "CTU-DLC", };
		map.put("20003", s20003);//四川
		
		String[] s20002 = { "TAO-PEK", "TAO-CAN", "TAO-CKG", "TNA-CAN",
				"TNA-PEK", "TNA-SHA", "TAO-SHA", "TNA-XMN", "PEK-TAO",
				"CAN-TAO", "SHA-TAO", "TNA-SZX", "TAO-SZX", "TNA-XIY" };
		map.put("20002", s20002);//山东
		
		String[] s20007 = { "XMN-PEK", "XMN-CAN", "PEK-XMN", "CAN-XMN",
				"XMN-SHA", "SHA-XMN", "FOC-CAN", "FOC-CGO", "XMN-SZX",
				"SZX-XMN", "CAN-FOC", "CGO-FOC", "XMN-TSN", "TSN-XMN"

		};
		
		map.put("20007", s20007);//厦门
		
		String[] s20012 = { "KMG-SZX", "NKG-KMG", "KMG-CAN", "KMG-CKG",
				"KMG-HRB", "KMG-JHG", "KMG-PVG", "KMG-HGH", "KMG-XIY",
				"KMG-CGO", "KMG-XMN", "KMG-TNA", "CAN-KMG", "KMG-CSX", };	
		map.put("20012", s20012);//昆明
		
		String[] s20013 = { "TSN-TAO", "TSN-HGH", "HGH-TSN", "TSN-NGB",
				"TAO-TSN", "TSN-BAV", "TSN-MDG", "TSN-INC", "URC-SYX",
				"TSN-DSN", "XIY-BAV", "XIY-URC", "XIY-NNG", "NNG-WUH"
		};
		map.put("20013", s20013);//天津
		
		String[] s20014 = { "KMG-PEK", "KMG-PVG", "KMG-FOC", "KMG-LJG",
				"KMG-SZX", "KMG-CGO", "KMG-SYX", "KMG-TCZ", "PEK-KMG",
				"FOC-KMG", "SYX-KMG", "SZX-KMG", "LJG-KMG", "KMG-BAV", };
		map.put("20014", s20014);//祥鹏
		
		String[] s20015 = { "CKG-SZX", "CKG-KWL", "URC-LHW", "CKG-HAK",
				"CKG-CAN", "CGO-DLC", "CKG-CGO", "KRL-CKG", "TYN-CKG",
				"CGO-ZUH", "KMG-JHG", "CAN-CKG", "CGO-KWE", "SZX-CKG" };
		map.put("20015", s20015);//西部
		
		String[] s20018 = { "YNT-DLC", "TSN-CAN", "TSN-NGB", "TSN-YNT",
				"TSN-CTU", "TSN-KWL", "TSN-SZX", "TSN-KMG", "TSN-HGH",
				"TSN-NNG", "TSN-SYX", "YNT-TSN", "CSX-HRB", "CSX-URC"

		};
		map.put("20018", s20018);
		
		String[] strs =map.get(channel);
		List<String> list=new ArrayList<String>();
		if(null!=strs && strs.length>0){
			for(String s :strs){
				list.add(s);
			}
			return list;
		}
		return TaskInfoXmlBean.getDomesticLines();
	}

}
